"""
上传C13项目报告信息到服务器
"""
import logging
import os

from src64.post_data import PostData
from src64.models.save_report_model import *


class PostReport:
    pos_LbaPWV = 75
    pos_RbaPWV = 74
    pos_Rabi = 76  # <0.9 存在动脉闭塞可能,0.9-1.4 正常,>1.4 钙化可能
    pos_Labi = 77

    # 男士动脉硬化基准数据,value数组从左到右依次为 柔软值高值,正常高值,稍硬高值
    man_data = {20: [1000, 1280, 1420], 30: [1010, 1304, 1440], 40: [1020, 1340, 1480], 50: [1070, 1400, 1560],
                60: [1140, 1510, 1700], 70: [1220, 1670, 1900], 80: [1330, 1850, 2120], 90: [1460, 2050, 2350]}
    woman_data = {20: [840, 1118, 1255], 30: [866, 1140, 1281], 40: [918, 1200, 1348], 50: [1000, 1333, 1492],
                  60: [1114, 1481, 1666], 70: [1255, 1681, 1892], 80: [1420, 1896, 2133], 90: [1600, 2118, 2380]}

    def __init__(self, conf, info):
        self.conf = conf
        self.info = info
        self.upload = PostData(conf, info)
        if conf.has_option('base', 'report_data_dir'):
            self.data_dir = conf['base']['report_data_dir']

    async def post_c13_report(self, data):
        """
        上传碳13报告信息到服务器
        :param data:
        :return:
        """
        result = data['result']
        value = data['value']
        if data and self.upload:
            img_url = None
            if data['img']:
                img_res = await self.upload.upload_file(data['img'])
                logging.getLogger('main').info('上传图片:{}'.format(img_res.__dict__))
                if img_res.code == 0:
                    img_url = img_res.resultMap.url
            check_sign_word = await self.upload.list_check_sign_word(data['no'], data['sex'])
            if check_sign_word.code == 0 and check_sign_word.data:
                check_sign_info = check_sign_word.data[0]
                sign_word_list = check_sign_info.signWordList
                if sign_word_list:
                    sign_word_info = sign_word_list[0]
                    sign_word_detail_list = [s for s in sign_word_info.signWordDetailList if result in s.signWordDetail]
                    if sign_word_detail_list:
                        sign_word_detail_info = sign_word_detail_list[0]
                        save_model = SaveReportModel()
                        save_model.deptId = check_sign_info.deptId
                        save_model.deptName = check_sign_info.deptName
                        save_model.registNo = check_sign_info.registNo
                        save_model.briefSummary = f'{sign_word_info.signWord}:{sign_word_detail_info.signWordDetail}'
                        save_model.isLisSummary = 0
                        save_model.isDelaySummary = 0
                        patientCheckItemList = PatientCheckItemList()
                        patientCheckItemList.patientCheckId = check_sign_info.patientCheckId
                        patientCheckItemList.itemId = check_sign_info.itemId
                        patientCheckItemList.itemName = check_sign_info.itemName
                        patientCheckItemList.itemType = check_sign_info.itemType
                        patientCheckSignWordList = PatientCheckSignWordList()
                        patientCheckSignWordList.signWord = sign_word_info.signWord
                        patientCheckSignWordList.signWordId = sign_word_info.signWordId
                        patientCheckSignWordList.signWordSummary = sign_word_detail_info.signWordDetail
                        patientCheckSignWordDetailList = PatientCheckSignWordDetailList()
                        patientCheckSignWordDetailList.signWordDetail = sign_word_detail_info.signWordDetail
                        patientCheckSignWordDetailList.signWordDetailId = sign_word_detail_info.signWordDetailId
                        patientCheckSignWordDetailList.conclusionWord = sign_word_detail_info.conclusionWord
                        patientCheckSignWordDetailList.conclusionWordId = sign_word_detail_info.conclusionWordId
                        patientCheckSignWordDetailList.severeDegree = sign_word_detail_info.severeDegree
                        patientCheckSignWordDetailList.signWordDetailSummary = f'阳性({value})' if result == '阳性' else ''
                        patientCheckSignWordList.patientCheckSignWordDetailList = [
                            patientCheckSignWordDetailList.__dict__]
                        patientCheckItemList.patientCheckSignWordList = [patientCheckSignWordList.__dict__]
                        patientCheckItemList.patientCheckPictureList = [img_url] if img_url else []
                        save_model.patientCheckItemList = [patientCheckItemList.__dict__]

                        save_res = await self.upload.save_check_report(save_model.__dict__)
                        logging.getLogger('main').info('上传结果:{}'.format(save_res.__dict__))
                        if save_res.code == 0:
                            await self.upload.complete_check(check_sign_info.registNo)

    async def get_result_by_data(self, LbaPWV, RbaPWV, age, sex):
        """
        根据左右血流速度计算当前症状,使用最大值进行计算
        :param sex: 性别,1男 0女
        :param LbaPWV:
        :param RbaPWV:
        :param age: 年龄
        :return: 柔软,正常范围内,稍硬,动脉硬化
        """
        pwv = max(LbaPWV, RbaPWV)
        # 在对应性别数据中,找到对应年龄的三个数值,分别为柔软高值,正常高值,稍硬高值
        [target_age] = \
            [x for x in (self.man_data if sex == 1 else self.woman_data) if age / x < 2 and age % x < 10]

        [soft, common, hard] = (self.man_data if sex == 1 else self.woman_data)[target_age]
        # 找到下一年龄段的数值,如果是90岁的,继续使用90的数据
        [soft_next, common_next, hard_next] = (self.man_data if sex == 1 else self.woman_data)[
            target_age if target_age == 90 else target_age + 10]
        # 这里将当前值,下一年龄段值,与年龄差(10岁)看做一个直角三角形,根据底边的长度按照比例计算高度
        soft_base = soft + (soft_next - soft) * (age % target_age / 10)
        common_base = common + (common_next - common) * (age % target_age / 10)
        hard_base = hard + (hard_next - hard) * (age % target_age / 10)
        if pwv <= soft_base:
            # 如果当前值小于柔软的高值,则一定是柔软
            return '柔软'
        elif pwv >= hard_base:
            # 如果大于高值,则一定是动脉硬化
            return '动脉硬化'
        elif common_base < pwv < hard_base:
            # 如果在正常高值与稍硬高值之间,则为稍硬
            return '稍硬'
        elif soft_base < pwv < common_base:
            # 如果在柔软高值与正常高值范围内,则为正常
            return '标准范围内'
        else:
            # 这里做异常处理
            return '后附报告'

    async def get_abi_result(self, Labi, Rabi):

        """
        <0.9 动脉闭塞可能性;0.9<x<1.4 正常值,>1.4血管钙化
        :param Labi:
        :param Rabi:
        :return:
        """
        abi = max(Labi, Rabi)
        if abi < 0.9:
            return '怀疑因为血管的堵塞而不能评价血管的硬度。', -1
        elif abi > 1.4:
            return '血管钙化，动脉弹性受损。', 1
        else:
            return '', 0

    async def post_dm_report(self, data):
        """
        上传动脉硬化报告信息到服务器
        :param data:
        :return:
        """
        logging.getLogger('main').info('上传数据:{}'.format(data))
        if data and self.upload:
            reg_no = data['no']
            img_url = []
            result = ''  # 检查结果
            abi_result = ''  # abi 指标对应的结果
            img_list = data['img']
            if img_list:
                img_list.sort(reverse=True)
                for img in img_list:
                    img_res = await self.upload.upload_file(img)
                    logging.getLogger('main').info('上传图片:{}'.format(img_res.__dict__))
                    if img_res and img_res.code == 0:
                        img_url.append(img_res.resultMap.url)
                    else:
                        logging.getLogger('main').error('上传图片出错:{}'.format(img_res.__dict__))
            if self.data_dir:
                files = os.listdir(self.data_dir)
                if files:
                    for f_name in files:
                        if reg_no in f_name:
                            with open(self.data_dir + '\\' + f_name, 'r') as f:
                                ls = f.readlines()
                                if ls and len(ls) > 1:
                                    l = ls[1].split(',')
                                    age = int(l[6])
                                    LbaPwv = int(l[self.pos_LbaPWV])
                                    RbaPwv = int(l[self.pos_RbaPWV])
                                    Labi = float(l[self.pos_Labi])
                                    Rabi = float(l[self.pos_Rabi])
                                    result = await self.get_result_by_data(LbaPwv, RbaPwv, age, int(l[4]))
                                    abi_result, abi_status = await self.get_abi_result(Labi, Rabi)
                                    if abi_status != 0:
                                        result = '其他'
                            break
            else:
                logging.getLogger('main').error('没有找到动脉硬化数据目录')
            if not result and not img_list:
                # 如果没有结果并且没有图片,则不再走下面的流程
                logging.getLogger('main').error('报告数据不完整:result:{},img:{}'.format(result, img_list))
                return
            check_sign_word = await self.upload.list_check_sign_word(reg_no, data['sex'])
            if check_sign_word.code == 0 and check_sign_word.data:
                check_sign_info = check_sign_word.data[0]
                sign_word_list = check_sign_info.signWordList
                if sign_word_list:
                    sign_word_info = sign_word_list[0]
                    sign_word_detail_list = [s for s in sign_word_info.signWordDetailList if
                                             (result in s.signWordDetail)]
                    if sign_word_detail_list:
                        save_model = SaveReportModel()
                        save_model.deptId = check_sign_info.deptId
                        save_model.deptName = check_sign_info.deptName
                        save_model.registNo = check_sign_info.registNo
                        save_model.briefSummary = f'{sign_word_info.signWord}:'
                        save_model.isLisSummary = 0
                        save_model.isDelaySummary = 0
                        patientCheckItemList = PatientCheckItemList()
                        patientCheckItemList.patientCheckId = check_sign_info.patientCheckId
                        patientCheckItemList.itemId = check_sign_info.itemId
                        patientCheckItemList.itemName = check_sign_info.itemName
                        patientCheckItemList.itemType = check_sign_info.itemType
                        patientCheckSignWordList = PatientCheckSignWordList()
                        patientCheckSignWordList.signWord = sign_word_info.signWord
                        patientCheckSignWordList.signWordId = sign_word_info.signWordId
                        for sign_word_detail_info in sign_word_detail_list:
                            save_model.briefSummary += sign_word_detail_info.signWordDetail if abi_status == 0 else abi_result
                            patientCheckSignWordList.signWordSummary += sign_word_detail_info.signWordDetail if abi_status == 0 else abi_result
                            patientCheckSignWordDetailList = PatientCheckSignWordDetailList()
                            patientCheckSignWordDetailList.signWordDetail = sign_word_detail_info.signWordDetail
                            patientCheckSignWordDetailList.signWordDetailId = sign_word_detail_info.signWordDetailId
                            patientCheckSignWordDetailList.conclusionWord = sign_word_detail_info.conclusionWord
                            patientCheckSignWordDetailList.conclusionWordId = sign_word_detail_info.conclusionWordId
                            patientCheckSignWordDetailList.severeDegree = sign_word_detail_info.severeDegree
                            patientCheckSignWordDetailList.signWordDetailSummary = sign_word_detail_info.signWordDetail if abi_status == 0 else abi_result
                            patientCheckSignWordList.patientCheckSignWordDetailList = [
                                patientCheckSignWordDetailList.__dict__]
                        patientCheckItemList.patientCheckSignWordList = [patientCheckSignWordList.__dict__]
                        patientCheckItemList.patientCheckPictureList = img_url
                        save_model.patientCheckItemList = [patientCheckItemList.__dict__]

                        save_res = await self.upload.save_check_report(save_model.__dict__)
                        if save_res.code == 0:
                            await self.upload.complete_check(check_sign_info.registNo)
